import axios from 'axios';
import type { AxiosInstance } from 'axios';

const token: string = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNzIwMDE4MDUzLCJpYXQiOjE3MTk0MTMyNTMsImp0aSI6IjE2ZjEwNzk1YjUyYjQxNTVhNzYxNDQyYTQ5Mzk1NTVkIiwidXNlcl9pZCI6MSwidXNlcm5hbWUiOiJzdSIsImRpc3RyaWN0IjoiRWxsZXJzbGllIn0.JayXEyXZVtsY9DlKwK_6DNg5D2EZ3nIQlKFrLi97LY8';
localStorage.setItem('token', token);

const baseURL: string = "";

const instance: AxiosInstance = axios.create({
  baseURL,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 添加请求拦截器，设置 token
instance.interceptors.request.use((config: any) => {
  const token = localStorage.getItem("token");
  if (token) {
    config.headers.Authorization = `Bearer ${token}`;
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

// 响应拦截器，处理错误
instance.interceptors.response.use((response) => response.data, (error) => {
  if (error.response) {
    // 处理服务器返回的错误状态码
    console.error(`服务器错误: ${error.response.status}`);
  } else if (error.request) {
    // 处理请求未发送的情况
    console.error('请求未发送');
  } else {
    // 处理其他错误
    console.error('发生错误:', error.message);
  }
  return Promise.reject(error);
});

// GET 方法封装
const getRequest = async (url: string, params: object = {}): Promise<any> => {
  try {
    const response = await instance.get(url, { params });
    return response;
  } catch (error) {
    throw error;
  }
};

// POST 方法封装
const postRequest = async (url: string, data: object = {}): Promise<any> => {
  try {
    const response = await instance.post(url, data);
    return response;
  } catch (error) {
    throw error;
  }
};

// PATCH 方法封装
const patchRequest = async (url: string, data: object = {}): Promise<any> => {
  try {
    const response = await instance.patch(url, data);
    return response;
  } catch (error) {
    throw error;
  }
};

export { getRequest, postRequest, patchRequest };